<template>
  <base-modal :width="modAlProps.width" :isVisible="props.isVisible" :title="modAlProps.title" :buttons="buttons"
    @handleOk="buttonMessage" @handleCancle="handleCancle" class="content_move_modal">
    <template v-slot:body>
      <div>
        <a-form name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
          ref="columnFrom">
          <a-form-item :label="'目标站点'">
            <a-select v-model:value="siteId" @select="siteChange" placeholder="请选择" :options="siteOptions" :fieldNames="{
              label: 'siteName',
              value: 'id',
            }"></a-select>
          </a-form-item>
          <a-form-item :label="'选择栏目'" v-if="gData && gData.length > 0">
            <a-input v-model:value="searchValue" placeholder="搜索栏目名称">
              <template #suffix>
                <i class="iconfont icon-search"></i>
              </template>
            </a-input>
          </a-form-item>

          <a-form-item :label="''" v-if="gData && gData.length > 0">
            <div class="openorclose" @click="openorclose" v-show="!isOpen">
              <span>全部收起</span>
              <i class="iconfont icon-up" style="font-size: 24px"> </i>
            </div>
            <div class="openorclose" @click="openorclose" v-show="isOpen">
              <span>全部展开</span>
              <i class="iconfont icon-down" style="font-size: 24px"> </i>
            </div>
            <a-tree :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :tree-data="gData"
              @expand="onExpand" :fieldNames="fieldNames" class="atree">
              <template #title="record">
                <!-- <span>{{ record.id }}</span> -->

                <a-checkbox v-model:checked="record.selected" @click="checkClick(record)" v-if="!record.children"
                  style="margin-right: 12px;"></a-checkbox>
                <span v-if="record.channelName.indexOf(searchValue) > -1" @click.stop>
                  {{
                    record.channelName.substr(0, record.channelName.indexOf(searchValue))
                  }}
                  <span style="color: var(--theme_button_bg_color, #f50); ">{{ searchValue }}</span>
                  {{
                    record.channelName.substr(
                      record.channelName.indexOf(searchValue) + searchValue.length
                    )
                  }}
                </span>
                <span v-else @click.stop>{{ record.channelName }}</span>
              </template>
            </a-tree>
          </a-form-item>
        </a-form>
      </div>
    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, defineComponent, watch } from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import request from "@/api/index";
import { Modal, message } from "ant-design-vue";
import type { TreeProps } from "ant-design-vue";
import getters from "@/store/getters";
import { array } from "vue-types";
//interface
interface Options {
  [propName: string | number]: any;
}
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  contentIds: {
    type: Array,
    default: [],
  },
  channelId: {
    type: [Number, String],
    default: null,
  },
});
//data
//模态框数据
const modAlProps = reactive<Options>({
  width: "M",
  title: "移动",
});
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "channelName",
  key: "id",
});
const formState = ref<dataSourceType>({});
//模态框button按钮个数和文案修改

let buttons = ref<Options[]>([
  {
    text: "移动",
    "html-type": "submit",
  },
]);
const siteOptions = ref<dataSourceType[]>([]);
const siteId = ref<any[]>([]);
const userInfo = getters.userInfo();
const expandedKeys = ref<(string | number)[]>([]);
const searchValue = ref<string>("");
const autoExpandParent = ref<boolean>(true);
const gData = ref<TreeProps["treeData"]>();
const dataList: TreeProps["treeData"] = [];
const isOpen = ref<boolean>(true); //是否展开或收起.
const channelId = ref<number | string>();
const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

watch(searchValue, (value) => {
  parentKey.value = [];
  if (value) {
    dataList.map((item: any) => {
      getParentKey(value, item);
    });
  }
  expandedKeys.value = parentKey.value;
  searchValue.value = value;
  autoExpandParent.value = true;
});
const parentKey = ref<(string | number)[]>([]);
const getParentKey = (value: string | number, node: any) => {
  if (node.channelName.indexOf(value) > -1) {
    // parentKey = node.id;
    parentKey.value.push(node.id);
    if (node.children) {
      node.children.map((item: any) => {
        getParentKey(value, item);
      });
    }
  } else {
    if (node.children) {
      node.children.map((item: any) => {
        getParentKey(value, item);
      });
    }
  }
};

//获取站点层级树列表
const fetchSiteTreeList = async () => {
  const data: {} = {
    // orgId: userInfo.orgId,
    userId: userInfo.userId,
    allPermissions: true,
  };
  siteOptions.value = await request.fetchContentSiteList(data);
  // fetchChannelChannelTree();
};
// 选择站点
const siteChange = async (val: any) => {
  fetchChannelListBySiteId(val);
};
//获取栏目层级树列表
const fetchChannelListBySiteId = async (val: any) => {
  let params = {
    allPermFilter: true,
    siteId: val,
  };
  let data = await request.fetchChannelListBySiteId(params);
  gData.value = data;
  dataList.push(...data);
};
const checkClick = async (val: any) => {
  if (val.selected == false) {
    channelId.value = val.id;
  } else {
    channelId.value = "";
  }
};
const openorclose = () => {
  isOpen.value = !isOpen.value;
  if (isOpen.value) {
    expandedKeys.value = [];
  } else {
    traversal(dataList);
  }
};
const traversal = (data: any) => {
  data.map((item: any) => {
    parentKey.value.push(item.id);
    if (item.children) {
      traversal(item.children);
    }
  });
  expandedKeys.value = parentKey.value;
};
// 移动调取接口
const buttonMessage = async (msg: dataSourceType) => {
  let params = {
    contentIds: props.contentIds,
    channelId: channelId.value,
    // contentIds: [],
  };
  request
    .fetchContentMove(params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        handleOk();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const emits = defineEmits(["handleOk", "handleCancle"]);
const handleOk = () => {
  emits("handleOk");
};

const handleCancle = (e: MouseEvent) => {
  emits("handleCancle", e);
};
//onmounted
onMounted(async () => {
  fetchSiteTreeList();
});
</script>

<style lang="scss" scoped>
::v-deep(.ant-form-item-label) {
  width: 80px;
}

::v-deep(.atree) {
  margin-left: 80px;
}

.icon-search {
  font-size: 14px !important;
  color: rgba(0, 0, 0, 0.45);
}

.openorclose {
  margin-left: 80px !important;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 16px;
  font-size: 14px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  height: 24px;

  &:hover {
    color: var(--theme_button_bg_color, #1F6DED);

    .iconfont {
      color: var(--theme_button_bg_color, #1F6DED);
    }
  }

  .iconfont {
    margin-left: 5px;
    color: rgba(0, 0, 0, 0.85);
  }
}

.content_move_modal {
  .ant-form-item:nth-of-type(2) {
    margin-bottom: 16px;
  }

  .ant-form-item:nth-last-of-type(1) {
    margin-bottom: 0;
  }
}
</style>
